package com.sto.stoapp.activity.scanner.inquiry;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.http.BaseMessage;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.status.OperateEnumTable;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.DateUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHomeActivity;

public class TimeInquiryActivity extends StoHomeActivity {
	StoHhmEditText startDateET, startTimeET, lastDateET, lastTimeET;
	Button startDateBut, startTimeBut, lastDateBut, lastTimeBut, submit;
	RadioGroup group;
	List<Info> infos = new ArrayList<TimeInquiryActivity.Info>();
	InfoAdapter adapter;
	ListView listView;
	final int HANDLER_DATA = 1;
	TimeInquiryThread thread;
	String action;
	boolean isAdimin = false;
	RadioButton jobNumType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.time_inquiry_layout);
		action = getIntent().getStringExtra(HomeBroadAction.BROAD_TYPE);// 区分操作界面进去的查询
		if (HomeBroadAction.ADMINISTRATOR_BROAD.equals(action)) {
			isAdimin = true;
		} else {
			isAdimin = false;
		}
		this.setTitleBottom("时间段 查询", action);
		if (isAdimin && !"".equals(getIntent().getStringExtra("inquiry_type"))) {// 区分管理员进去的
			// 查询
			// 表类型
			action = getIntent().getStringExtra("inquiry_type");
			if (action.equals(BaseMessage.SCANNER_VERSION)) {
				action = HomeBroadAction.SCANNER_MAN_BROAD;
			} else if (action.equals(BaseMessage.CENTER_VERSION)) {
				action = HomeBroadAction.CENTER_BROAD;
			} else if (action.equals(BaseMessage.SALES_VERSION)) {
				action = HomeBroadAction.SALES_MAN_BROAD;
			} else if (action.equals(BaseMessage.AVIATION_A_VERSION)) {
				action = HomeBroadAction.AVIATION_BROAD;
			}

		}
		initView();
		initListener();

	}

	private void initListener() {
		startDateBut.setOnClickListener(mOnClickListener);
		startTimeBut.setOnClickListener(mOnClickListener);
		lastDateBut.setOnClickListener(mOnClickListener);
		lastTimeBut.setOnClickListener(mOnClickListener);
		submit.setOnClickListener(mOnClickListener);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Info info = (Info) adapter.getItem(arg2);
				Intent intent = new Intent(TimeInquiryActivity.this,
						ResultInfoShowActivity.class);

				String startDate = startDateET.getText().toString();
				String startTime = startTimeET.getText().toString();
				String endDate = lastDateET.getText().toString();
				String endTime = lastTimeET.getText().toString();

				intent.putExtra(HomeBroadAction.BROAD_TYPE, action);
				intent.putExtra("start", startDate + " " + startTime + ":00");
				intent.putExtra("end", endDate + " " + endTime + ":00");
				intent.putExtra("table_name", info.tableName);
				intent.putExtra("isAdimin", isAdimin);
				startActivity(intent);
			}
		});
	}

	private void initView() {
		jobNumType = (RadioButton) findViewById(R.id.this_job_number);
		if (isAdimin) {
			jobNumType.setText("本巴枪");
		} else {
			jobNumType.setText("本工号");
		}

		startDateET = (StoHhmEditText) findViewById(R.id.start_date);
		startDateET.setText(DateUtil.getTodayDate("-"));
		startTimeET = (StoHhmEditText) findViewById(R.id.start_time);
		startTimeET.setText("00:00");
		lastDateET = (StoHhmEditText) findViewById(R.id.last_date);
		lastDateET.setText(DateUtil.getTodayDate("-"));
		lastTimeET = (StoHhmEditText) findViewById(R.id.last_time);
		lastTimeET.setText(DateUtil.getNowTime(":"));
		startDateBut = (Button) findViewById(R.id.start_day);
		startTimeBut = (Button) findViewById(R.id.start_hour);
		lastDateBut = (Button) findViewById(R.id.last_day);
		lastTimeBut = (Button) findViewById(R.id.last_hour);
		group = (RadioGroup) findViewById(R.id.job_number_type);
		submit = (Button) findViewById(R.id.comfirm);
		submit.setFocusable(true);
		submit.setText("开始查询");
		listView = (ListView) findViewById(R.id.list);
		adapter = new InfoAdapter(this, infos);
		listView.setAdapter(adapter);

	}

	OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.start_day:

				dateSetDialog(R.id.start_day);
				break;
			case R.id.start_hour:
				timeSetDialog(R.id.start_hour);
				break;
			case R.id.last_day:
				dateSetDialog(R.id.last_day);
				break;
			case R.id.last_hour:
				timeSetDialog(R.id.last_hour);
				break;
			case R.id.comfirm:
				doInquiry();
			default:
				break;
			}

		}

	};

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case HANDLER_DATA:
				thread.cancelDialog();
				infos = (List<Info>) msg.obj;
				if (infos.size() == 0) {
					Helper.showSoundToast(TimeInquiryActivity.this, "没有扫描数据",
							false);
					return;
				}
				adapter.notifyDataSetChanged();

				break;

			default:
				break;
			}
		}
	};

	/**
	 * 查询操作
	 */
	private void doInquiry() {
		if (checkDate()) {
			infos.clear();

			thread = new TimeInquiryThread(this, startDateET.getText()
					.toString(), lastDateET.getText().toString(), startTimeET
					.getText().toString(), lastTimeET.getText().toString(),
					mHandler, infos);
			thread.start();
		} else {
			Helper.showSoundToast(this, "开始时间要小于结束时间", false);
		}

	}

	/**
	 * 检测时间是否不符合 时间 结束要大于开始
	 * 
	 * @return
	 */
	private boolean checkDate() {
		long startDate = Long.parseLong(startDateET.getText().toString()
				.replace("-", ""));
		long lastDate = Long.parseLong(lastDateET.getText().toString()
				.replace("-", ""));
		if (startDate < lastDate)
			return true;

		int startTime = Integer.parseInt(startTimeET.getText().toString()
				.replace(":", ""));
		int lastTime = Integer.parseInt(lastTimeET.getText().toString()
				.replace(":", ""));
		if ((startDate == lastDate) && (startTime < lastTime))
			return true;
		return false;
	}

	// 获取时间dialog
	private void timeSetDialog(final int id) {
		final TimePicker timePicker = new TimePicker(this);
		int hour = timePicker.getCurrentHour();
		int minute = timePicker.getCurrentMinute();
		OnTimeSetListener timeListener = new OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				String min = "" + minute;
				if (minute < 10)
					min = "0" + min;

				String time = hourOfDay + ":" + min;

				if (id == R.id.start_hour) {
					startTimeET.setText(time);
				} else {
					lastTimeET.setText(time);
				}

			}
		};
		TimePickerDialog timeDialog = new TimePickerDialog(this, timeListener,
				hour, minute, true);
		timeDialog.show();
	}

	class TimeInquiryThread extends BaseThread {
		Context context;
		String startDate, endDate, startTime, endTime;
		Handler handler;
		List<Info> infos;

		public TimeInquiryThread(Context context, String startDate,
				String endDate, String startTime, String endTime,
				Handler handler, List<Info> infos) {
			super(context);
			this.endDate = endDate;
			this.endTime = endTime;
			this.startDate = startDate;
			this.startTime = startTime;
			this.context = context;
			this.handler = handler;
			showDialog();
			this.infos = infos;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			String jobNumber;
			if (isAdimin) {
				jobNumber = null;
			} else {
				jobNumber = StoFilePreference.getInstance(context)
						.getUserCode();
			}
			List<EnumTableNames> tableNames = null;
			if (HomeBroadAction.AVIATION_BROAD.equals(action)) {
				tableNames = OperateEnumTable.getAviationTables();
			} else if (HomeBroadAction.CENTER_BROAD.equals(action)) {
				tableNames = OperateEnumTable.getCenterTables();
			} else if (HomeBroadAction.SCANNER_MAN_BROAD.equals(action)) {
				tableNames = OperateEnumTable.getScannerTables();
			} else if (HomeBroadAction.SALES_MAN_BROAD.equals(action)) {
				tableNames = OperateEnumTable.getSaleTables();
			} else if (HomeBroadAction.AVIATION_SCANNER_BROAD.equals(action)) {
				tableNames = OperateEnumTable.getAviationScanTables();
			} else if (HomeBroadAction.PICKER_BROAD.equals(action)) {
				tableNames = OperateEnumTable.getAviationPickerTables();
			} else {
				tableNames = OperateEnumTable.getAllTables();
			}
			for (EnumTableNames enumc : tableNames) {
				if (!"".equals(enumc.getTableName())) {
					Info info = new Info();
					info.scanType = getString(Integer.parseInt(enumc
							.getScanTypeName()));
					StoDataBaseOperation mgr = StoDataBaseOperation
							.getInstance(context);
					info.sum = mgr.getCountByStateAndJob(enumc, jobNumber,
							null, startDate + " " + startTime + ":00", endDate
									+ " " + endTime + ":00");
					info.sendAmount = mgr.getCountByStateAndJob(enumc,
							jobNumber, "已",
							startDate + " " + startTime + ":00", endDate + " "
									+ endTime + ":00");
					info.tableName = enumc;
					info.unSendAmount = info.sum - info.sendAmount;
					infos.add(info);
				}
			}
			Message msg = handler.obtainMessage();
			msg.what = HANDLER_DATA;
			msg.obj = infos;
			handler.sendMessage(msg);

		}

	}

	// 获取日期的Dialog
	private void dateSetDialog(final int id) {
		final DatePicker datePicker = new DatePicker(this);
		int year = datePicker.getYear();
		int month = datePicker.getMonth();
		int dayOfMonth = datePicker.getDayOfMonth();

		OnDateSetListener callBack = new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {

				int month = monthOfYear + 1;
				String strMonth = null;
				String strDayOfMonth = null;
				if (0 < month && month < 10) {
					strMonth = "0" + month;
				} else {
					strMonth = "" + month;
				}
				if (0 < dayOfMonth && dayOfMonth < 10) {
					strDayOfMonth = "0" + dayOfMonth;
				} else {
					strDayOfMonth = "" + dayOfMonth;
				}
				String date = new StringBuilder().append(year).append("-")
						.append(strMonth).append("-").append(strDayOfMonth)
						.toString();
				if (id == R.id.start_day) {
					startDateET.setText(date);

				} else if (id == R.id.last_day) {
					lastDateET.setText(date);
				}
			}
		};
		DatePickerDialog datePickerDialog = new DatePickerDialog(this,
				callBack, year, month, dayOfMonth);

		datePickerDialog.show();
	}

	static class Info {
		public String scanType;
		public long sum;
		public long unSendAmount;
		public long sendAmount;
		public EnumTableNames tableName;
	}

	static class InfoAdapter extends BaseAdapter {
		List<Info> infos;
		Context c;

		public InfoAdapter(Context c, List<Info> infos) {
			this.c = c;
			this.infos = infos;
		}

		@Override
		public int getCount() {
			return infos.size();
		}

		@Override
		public Object getItem(int position) {
			return infos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@SuppressLint("ResourceAsColor")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Hold hold;
			if (convertView == null) {
				convertView = LayoutInflater.from(c).inflate(
						R.layout.time_inquiry_item, null);
				hold = new Hold();
				hold.scanTypeTV = (TextView) convertView
						.findViewById(R.id.scan_type);
				hold.sendCountTV = (TextView) convertView
						.findViewById(R.id.send_count);
				hold.sumTV = (TextView) convertView.findViewById(R.id.sum);
				hold.unsendCountTV = (TextView) convertView
						.findViewById(R.id.unsend_count);
				convertView.setTag(hold);
			} else {
				hold = (Hold) convertView.getTag();
			}
			hold.scanTypeTV.setText(infos.get(position).scanType);
			hold.sendCountTV.setText("" + infos.get(position).sendAmount);
			hold.sumTV.setText("" + infos.get(position).sum);
			hold.unsendCountTV.setText("" + infos.get(position).unSendAmount);
			return convertView;
		}

	}

	static class Hold {
		TextView scanTypeTV;
		TextView sumTV;
		TextView sendCountTV;
		TextView unsendCountTV;
	}
}
